#include "checklatestversion.h"
#include "service/downloader.h"
#include "service/service.h"
#include "utils/packs.h"
#include <QDateTime>
#include <QFile>
#include <QNetworkAccessManager>
#include <QtDebug>

namespace yc {

CheckLatestVersion::CheckLatestVersion(Service* service, const QString& upgrade_url,
                                       const QString& major_version, const QString& full_version,
                                       const QDateTime& build_date, const QString& local_file_name,
                                       int timeout, QObject* parent)
    : QObject(parent),
      major_version_(major_version),
      full_version_(full_version),
      build_date_(build_date),
      local_file_name_(local_file_name)
{
    QString url = QString("%1?t=%2")
                          .arg(upgrade_url)
                          .arg(QDateTime(QDate(2018, 1, 1), QTime(12, 0, 0))
                                       .msecsTo(QDateTime::currentDateTime()));

    QList<yc::DownloadResource> resources;
    resources.push_back(yc::DownloadResource { url, local_file_name });

    yc::Downloader* t =
            new yc::Downloader(service, QString(), resources, QString(), 0, true, timeout, 1, this);
    connect(t, &yc::Downloader::finished, this, &CheckLatestVersion::onDownloadXmlFinished,
            Qt::QueuedConnection);
    connect(t, &yc::Downloader::failed, this, [this](int, const QString&) {
        Q_EMIT finished(false, false, QString(), QString(), QString());
    });
    t->start();
    qDebug() << "check version: " << build_date << major_version << full_version;
}

void CheckLatestVersion::onDownloadXmlFinished()
{
    bool new_version = false;
    bool necessary = false;
    QString new_major_version;
    QString new_full_version;
    QString date;
    Packs packs(local_file_name_);
    if (packs.exist(full_version_)) {
        QList<Pack> next_packs = packs.nextPacks(full_version_);
        QList<Pack>::const_iterator it = next_packs.constBegin();
        QList<Pack>::const_iterator end = next_packs.constEnd();
        if (it != end) {
            new_version = true;
            const Pack& p = next_packs.constLast();
            new_major_version = p.app_version;
            new_full_version = p.version;
            date = p.date;
            necessary = (p.mode == Pack::kNecessary);
        }
    } else {
        const QString full_ver { major_version_ + "_full_package" };
        Pack p = packs.pack(full_ver);
        if (!p.version.isEmpty()
            && build_date_ < QDateTime::fromString(p.date, "yyyy/MM/dd hh:mm")) {
            new_version = true;
            new_major_version = p.app_version;
            new_full_version = full_ver;
            date = p.date;
            necessary = (p.mode == Pack::kNecessary);
        }
    }
    Q_EMIT finished(new_version, necessary, new_major_version, new_full_version, date);
}

} // namespace yc
